package com.wing.warehouse.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.chanjet.entity.shelfSpace.InvLocationCreateRequest;
import com.wing.chanjet.entity.shelfSpace.InvLocationQueryResponse;
import com.wing.chanjet.entity.shelfSpace.InvLocationWarehouseCreateRequest;
import com.wing.chanjet.feign.ChanjetClient;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.warehouse.dao.WarehouseDao;
import com.wing.warehouse.dao.WarehouseShelfSpaceDao;
import com.wing.warehouse.model.entity.Warehouse;
import com.wing.warehouse.model.entity.WarehouseShelfSpace;
import com.wing.warehouse.model.request.WarehouseShelfFlatSpaceForm;
import com.wing.warehouse.model.request.WarehouseShelfSpaceForm;
import com.wing.warehouse.model.response.WarehouseShelfSpaceVO;
import com.wing.web.excel.DeviceExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ShelfSpaceExcelIn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 仓库货架货位-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class WarehouseShelfSpaceServiceImpl extends ServiceImpl<WarehouseShelfSpaceDao, WarehouseShelfSpace> implements WarehouseShelfSpaceService {

    @Autowired
    ChanjetClient chanjetClient;

    @Override
    public int add(WarehouseShelfSpaceForm warehouseShelfSpaceForm) {

        //校验

        WarehouseShelfSpace warehouseShelfSpace =new WarehouseShelfSpace();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WarehouseShelfSpace.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseShelfSpaceForm, warehouseShelfSpace, copyOptions);

        return baseMapper.insert(warehouseShelfSpace);
    }

    @Override
    public List<WarehouseShelfSpaceVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<WarehouseShelfSpaceVO> pageList4app(Page page, Map<String, Object> params) {
        List<WarehouseShelfSpaceVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WarehouseShelfSpaceVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }
    @Override
    public int disableByShelfId(Long shelfId) {
        return baseMapper.disableByShelfId(shelfId);
    }

    @Override
    public int updateShelfSpaceById(WarehouseShelfSpace warehouseShelfSpace) {
        return baseMapper.updateShelfSpaceById(warehouseShelfSpace);
    }

    @Override
    public WarehouseShelfSpaceVO findByCode(String code) {
        return baseMapper.findByCode(code);
    }

    @Override
    public List<WarehouseShelfSpaceVO> getShelfSpace(String skuCode, Long warehouseId) {
        return baseMapper.getShelfSpace(skuCode, warehouseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addFlat(WarehouseShelfFlatSpaceForm warehouseShelfFlatSpaceForm) {

        List<WarehouseShelfSpace> saveList = new ArrayList<>();
        if(warehouseShelfFlatSpaceForm.getFirstCode() == null || ! warehouseShelfFlatSpaceForm.getFirstCode().matches(".*\\d$")){
            return JsonResult.fail( 1001,"格式必须为数字结尾");
        }
        // 获取初始化的编码
        String prefix = warehouseShelfFlatSpaceForm.getFirstCode().replaceAll("\\d+$", ""); // 提取前面的非数字部分
        String suffix = warehouseShelfFlatSpaceForm.getFirstCode().replaceAll(".*?(\\d+)$", "$1"); // 提取最后的数字部分
        Integer firstNum = Integer.parseInt(suffix);
        WarehouseShelfSpace wss = baseMapper.selectLastNumByPrefix(prefix,prefix.length(),firstNum);
        if(ObjectUtil.isNotNull(wss)){
            return JsonResult.fail(1002,"最大库位编号为："+wss.getCode()+",请设置比它更大的值");
        }
        for ( int i = firstNum ; i< firstNum+ warehouseShelfFlatSpaceForm.getSpaceNum() ; i++){
            WarehouseShelfSpace warehouseShelfSpace =new WarehouseShelfSpace();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseShelfSpace.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseShelfFlatSpaceForm, warehouseShelfSpace, copyOptions);
            warehouseShelfSpace.setCode(prefix+(i));
            // 货架Id 不能为空 默认 -1  表示 平仓货架
            warehouseShelfSpace.setShelfId(-1L);
            saveList.add(warehouseShelfSpace);
        }
        if(saveBatch(saveList)){
            return JsonResult.success();
        }else{
            return JsonResult.fail("保存失败");

        }
    }

    @Autowired
    WarehouseDao warehouseDao;

    @Override
    public JsonResult syncSpaceCjt() {
        JsonResult<List<InvLocationQueryResponse>> shelfSpaceData = chanjetClient.getShelfSpaceData("");
        List<InvLocationQueryResponse> shelfSpaceDataData = shelfSpaceData.getData();
        for (InvLocationQueryResponse shelfSpaceDataDatum : shelfSpaceDataData) {
            WarehouseShelfSpace warehouseShelfSpace =new WarehouseShelfSpace();

            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseShelfSpace.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(shelfSpaceDataDatum, warehouseShelfSpace, copyOptions);
            warehouseShelfSpace.setCode(shelfSpaceDataDatum.getCode());
            warehouseShelfSpace.setName(shelfSpaceDataDatum.getName());
            warehouseShelfSpace.setShelfId(0l);
            warehouseShelfSpace.setWarehouseAreaId(0l);
            LambdaQueryWrapper<Warehouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Warehouse::getCode,shelfSpaceDataDatum.getWarehouseCode());
            Warehouse warehouses = warehouseDao.selectOne(lambdaQueryWrapper);
            if(warehouses!=null){
                warehouseShelfSpace.setWarehouseId(warehouses.getId());
            }

            //数据库中已经存在货位了则进行修改
            LambdaQueryWrapper<WarehouseShelfSpace> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(WarehouseShelfSpace::getCode,shelfSpaceDataDatum.getCode());
            WarehouseShelfSpace warehouseShelfSpace1 = baseMapper.selectOne(lambdaQueryWrapper2);
            if(warehouseShelfSpace1!=null){
                warehouseShelfSpace.setId(warehouseShelfSpace1.getId());
                baseMapper.updateById(warehouseShelfSpace);
            }else{
                baseMapper.insert(warehouseShelfSpace);
            }

        }
        return JsonResult.success();
    }



    @Override
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"货位编码(*)","货位名称(*)","仓库编码(*)","仓库名称(*)"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();

        LambdaQueryWrapper<Warehouse> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(Warehouse::getHasPosition,true);
        List<Warehouse> warehouseList = warehouseDao.selectList(lambdaQueryWrapper2);
         if(CollectionUtil.isNotEmpty(warehouseList)){
            for (Warehouse warehouse :warehouseList) {
                tempStr.append(warehouse.getCode()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("2");
        }

        if(CollectionUtil.isNotEmpty(warehouseList)){
            for (Warehouse warehouse :warehouseList) {
                tempStr.append(warehouse.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("3");
        }
        DownExcelUtil.createExcelTemplate(response, request, "货位导入模板", Arrays.asList(headerArr), downData, indexArr);
    }

    @Override
    public void importExcel(List<ShelfSpaceExcelIn> list) {
         try {
            for(ShelfSpaceExcelIn shelfSpaceDataDatum:list){
                WarehouseShelfSpace warehouseShelfSpace =new WarehouseShelfSpace();

                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(WarehouseShelfSpace.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(shelfSpaceDataDatum, warehouseShelfSpace, copyOptions);
                warehouseShelfSpace.setCode(shelfSpaceDataDatum.getCode());
                warehouseShelfSpace.setName(shelfSpaceDataDatum.getName());
                warehouseShelfSpace.setShelfId(0l);
                warehouseShelfSpace.setWarehouseAreaId(0l);
                LambdaQueryWrapper<Warehouse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(Warehouse::getCode,shelfSpaceDataDatum.getWarehouseCode());
                Warehouse warehouses = warehouseDao.selectOne(lambdaQueryWrapper);
                if(warehouses!=null){
                    warehouseShelfSpace.setWarehouseId(warehouses.getId());
                }

                //数据库中已经存在货位了则进行修改
                LambdaQueryWrapper<WarehouseShelfSpace> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(WarehouseShelfSpace::getCode,shelfSpaceDataDatum.getCode());
                WarehouseShelfSpace warehouseShelfSpace1 = baseMapper.selectOne(lambdaQueryWrapper2);
                if(warehouseShelfSpace1!=null){
                    warehouseShelfSpace.setId(warehouseShelfSpace1.getId());
                    baseMapper.updateById(warehouseShelfSpace);
                }else{
                    baseMapper.insert(warehouseShelfSpace);
                }


                InvLocationCreateRequest invLocationCreateRequest = new InvLocationCreateRequest();
                invLocationCreateRequest.setCode(shelfSpaceDataDatum.getCode());
                invLocationCreateRequest.setName(shelfSpaceDataDatum.getName());
                invLocationCreateRequest.setMemo("后台导入添加货位！");

                InvLocationWarehouseCreateRequest invLocationWarehouseCreateRequest = new InvLocationWarehouseCreateRequest();
                invLocationWarehouseCreateRequest.setCode(shelfSpaceDataDatum.getWarehouseCode());
                invLocationWarehouseCreateRequest.setName(shelfSpaceDataDatum.getWarehouseName());

                invLocationCreateRequest.setWarehouse(invLocationWarehouseCreateRequest);
                //处理畅捷通 货位新增
                JsonResult jsonResult = chanjetClient.syncAddShelfSpaceData(invLocationCreateRequest);
                log.info("货位导入处理结果："+jsonResult);

            }

        }catch (Exception e){
            log.info("货位导入处理异常："+e);
        }



    }

    @Override
    public JsonResult cancel(Long id) {
         WarehouseShelfSpace warehouseShelfSpace1 = baseMapper.selectById(id);
        if(warehouseShelfSpace1!=null){
            warehouseShelfSpace1.setStatus(WarehouseShelfSpace.Status.cancel);
            baseMapper.updateById(warehouseShelfSpace1);
        }else{
            JsonResult.fail();
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult recover(Long id) {
        WarehouseShelfSpace warehouseShelfSpace1 = baseMapper.selectById(id);
        if(warehouseShelfSpace1!=null){
            warehouseShelfSpace1.setStatus(WarehouseShelfSpace.Status.enable);
            baseMapper.updateById(warehouseShelfSpace1);
        }else{
            JsonResult.fail();
        }
        return JsonResult.success();
    }

    @Override
    public WarehouseShelfSpaceVO getWarehouseInfoBySpaceCode(String warehouseShelfSpaceCode) {
        return baseMapper.getWarehouseInfoBySpaceCode(warehouseShelfSpaceCode);
    }


}
